package com.opages.netty.demo.lesson.dark_horse3;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author daizhong.liu
 * @create 2022-01-06 10:43
 **/
@Slf4j
public class StickyBagServer {
    public void start() {
        EventLoopGroup boss = new NioEventLoopGroup(1);
        EventLoopGroup worker = new NioEventLoopGroup(2);
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap()
//                    .option(ChannelOption.SO_RCVBUF,5)
                    .group(boss, worker)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            //以\n为分割符
                            ByteBuf delimiter = Unpooled.copiedBuffer("\n".getBytes(CharsetUtil.UTF_8));
                            ch.pipeline()
                                    //以定长16进行拆包
//                                    .addLast(new FixedLengthFrameDecoder(16))
                                    //以结束符\n进行拆包
//                                    .addLast(new DelimiterBasedFrameDecoder(64,delimiter))
                                    //以行结束，即以\n为结束符
                                    .addLast(new LineBasedFrameDecoder(64))
                                    .addLast(new LoggingHandler(LogLevel.DEBUG))
                                    .addLast(new ChannelInboundHandlerAdapter() {
                                        @Override
                                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                            // 连接建立时会执行该方法
                                            log.debug("connected {}", ctx.channel());
                                            super.channelActive(ctx);
                                        }

                                        @Override
                                        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                                            // 连接断开时会执行该方法
                                            log.debug("disconnect {}", ctx.channel());
                                            super.channelInactive(ctx);
                                        }
                                    });
                        }
                    });
            ChannelFuture channelFuture = serverBootstrap.bind(8889);
            log.debug("{} binding...", channelFuture.channel());
            channelFuture.sync();
            log.debug("{} bound...", channelFuture.channel());
            // 关闭channel
            channelFuture.channel().closeFuture().sync();
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
            log.debug("stop");
        }
    }
    public static void main(String[] args)  {
        new StickyBagServer().start();
    }
}
